import {ElMessage} from "element-plus"
import {useRouter} from "vue-router";
import {getUnreadMsg} from "@/api/index.js"
import Push from 'push.js'
import iNotify from 'title-notify'
import blinkTitle from "../../public/blinkTitle"

export function isRoot (){
  const obj = JSON.parse(localStorage.getItem('syhyDocManSys'))
  const root = obj.root
  const router = useRouter()
  if(root === null || root === undefined){
    router.push('/login')
    return ElMessage({
      message:"请先登录",
      type:'error'
    })
  } else if(root === 2){
    return false
  }
}

export function isAdmin(){
  const obj = JSON.parse(localStorage.getItem('syhyDocManSys'))
  const root = obj.root
  const router = useRouter()
  if(root === null || root === undefined){
    router.push('/login')
    return ElMessage({
      message:"请先登录",
      type:'error'
    })
  } else if(root === 0){
    return false
  }
}

export function computeDate (str) {
  return str.slice(0,10)
}


export function getTime() {
  const date = new Date()
  let year = date.getFullYear()
  let month = (date.getMonth() + 1).toString().padStart(2,'0')
  let day = date.getDate().toString().padStart(2,'0')
  let hour = date.getHours().toString().padStart(2,'0')
  let min = date.getMinutes().toString().padStart(2,'0')
  let sec = date.getSeconds().toString().padStart(2,'0')

  return`${year}-${month}-${day} ${hour}:${min}:${sec}`

}

export async function hasUnreadMessage (id) {
  const {data:res} = await getUnreadMsg({
    userId:id
  })
  if(res.code === 400 || res.code === 401){
    throw new Error('查询错误')
  } else if (res.code === 200){
    return true //有未读
  } else if (res.code === 201){
    return false //没有未读
  }
}

export function getUserInfo(){
  return JSON.parse(localStorage.getItem('syhyDocManSys'))
}


export function createMsg(message,type,plain){
  return  ElMessage({
    message,
    type,
    plain,
  })
}

export function hasEmptyValue(obj) {
  const keysToCheck = Object.keys(obj).filter(key => key!=='sealCopy');
  for (const key of keysToCheck) {
    const value = obj[key];
    if (typeof value ==='string' && value === '') {
      return false;
    } else if (value === null || value === undefined) {
      return false;
    }
  }
  return true;
}

export function clearObject(obj){
  if (obj === null || typeof obj!== "object") {
    return obj;
  }
  if (Array.isArray(obj)) {
    for (let i = 0; i < obj.length; i++) {
      obj[i] = clearObject(obj[i]);
    }
  } else {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        // 如果属性值是对象，递归调用clearObject进行处理
        if (typeof obj[key] === "object" && obj[key]!== null) {
          obj[key] = clearObject(obj[key]);
        } else {
          // 对于非对象属性值，直接将其设置为空（这里可根据实际需求调整清空的方式，比如数字设为0等）
          obj[key] = "";
        }
      }
    }
  }
  return obj;
}


export function turnToDatetime(dateStr){
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}


export function processSealFileJSON(jsonStr){
  return JSON.parse(jsonStr)
}


export function hasFinanceEmptyValue(obj) {
  const keysToCheck = Object.keys(obj).filter(key => key!=='sealCopy');
  for (const key of keysToCheck) {
    const value = obj[key];
    if (typeof value ==='string' && value === '' || value === [] || value === 0) {
      console.log(value)
      return false;
    } else if (value === null || value === undefined) {
      console.log(value)
      return false;
    } else if (typeof value === 'object' && value[1] === null || value === []) {
      console.log(value)
      return false;
    }
  }
  return true;
}

export function getFileExtension(mimeType) {
  // 定义 MIME 类型与文件扩展名的映射关系
  const mimeToExtensionMap = {
    // 图片类型
    'image/jpeg': 'jpg',
    'image/png': 'png',
    'image/gif': 'gif',
    'image/bmp': 'bmp',
    'image/svg+xml': 'svg',
    // 文档类型
    'application/pdf': 'pdf',
    'application/msword': 'doc',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
    'application/vnd.ms-excel': 'xls',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
    'application/vnd.ms-powerpoint': 'ppt',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
    // 文本类型
    'text/plain': 'txt',
    'text/html': 'html',
    'text/css': 'css',
    'text/javascript': 'js',
    // 压缩文件类型
    'application/zip': 'zip',
    'application/x-rar-compressed': 'rar',
    'application/x-7z-compressed': '7z'
  };

  // 根据 MIME 类型查找对应的文件扩展名
  return mimeToExtensionMap[mimeType] || null;
}

export function senMessage(message) {

  console.log(Notification.permission)

  if (window.Notification && Notification.permission === "granted") {
    new Notification(message)
  }
  // 如果用户没有选择是否显示通知
  // 注：因为在 Chrome 中我们无法确定 permission 属性是否有值，因此
  // 检查该属性的值是否是 "default" 是不安全的。
  else if (window.Notification && Notification.permission !== "denied") {
    Notification.requestPermission(function (status) {
      if (Notification.permission !== status) {
        Notification.permission = status;
      }
      // 如果用户同意了
      if (status === "granted") {
        new Notification(message)
      } else {
        alert(message)
      }
    });
  } else if (window.Notification && Notification.permission === "denied"){
    alert(message)
  }

}


export function isPDF(json){
  console.log(JSON.parse(json.file))
  return JSON.parse(json.file).mime === 'application/pdf';
}
